package cn.larry.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;

/**
 * This is created,
 * but not necessarily updated by me.
 * Therefore, AUTHOR is useless.
 * 2023/11/14 10:31
 *
 * @Version 1.0
 */
@Slf4j
public class ImageToBase64Utils {

    /**
     * 【方法1】图片转Base64字符串
     *
     * @param imgFilePath 图片全路径
     * @return 缺少前缀："data:image/png;base64,"
     */
    public static String imageToBase64Str1(String imgFilePath) {
        InputStream inputStream = null;
        byte[] data = null;
        try {
            inputStream = new FileInputStream(imgFilePath);
            data = new byte[inputStream.available()];
            inputStream.read(data);
        } catch (IOException e) {
            log.error("图片处理异常", e);
        } finally {
            try {
                if (inputStream != null)
                    inputStream.close();
            } catch (Exception e) {
            }
        }
        // 加编码
        Base64.Encoder encoder = Base64.getEncoder();
        if (data == null) {
            new RuntimeException("图片为空");
        }
        return encoder.encodeToString(data);
    }

    /**
     * 【方法2】图片转Base64字符串
     *
     * @param imagePath 图片全路径
     * @return 缺少前缀："data:image/png;base64,"
     */
    public static String imageToBase64Str2(String imagePath) {
        FileInputStream imageInputStream = null;
        try {
            imageInputStream = new FileInputStream(imagePath);
            byte[] imageBytes = new byte[imageInputStream.available()];
            imageInputStream.read(imageBytes);
            return Base64.getEncoder().encodeToString(imageBytes);
        } catch (Exception e) {
            log.error("imageToBase64Str Exception", e);
            return null;
        } finally {
            try {
                if (imageInputStream != null)
                    imageInputStream.close();
            } catch (Exception e) {
            }
        }
    }

    /**
     * 图片文件流转Base64字符串
     *
     * @param imageFileInputStream 图片文件流
     * @return 缺少前缀："data:image/png;base64,"
     */
    public static String imageInputStreamToBase64Str3(FileInputStream imageFileInputStream) {
        if (imageFileInputStream == null)
            return null;
        try {
            byte[] imageBytes = new byte[imageFileInputStream.available()];
            imageFileInputStream.read(imageBytes);
            return Base64.getEncoder().encodeToString(imageBytes);
        } catch (Exception e) {
            log.error("imageToBase64Str Exception", e);
            return null;
        } finally {
            try {
                if (imageFileInputStream != null)
                    imageFileInputStream.close();
            } catch (Exception e) {
            }
        }
    }

    /**
     * 图片URL转Base64字符串
     *
     * @param imageUrl 图片URL地址
     * @return 缺少前缀："data:image/png;base64,"
     */
    public static String imageUrlToBase64Str(String imageUrl) {
        ByteArrayOutputStream outPut = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        InputStream inStream = null;
        try {
            // 创建URL
            URL url = new URL(imageUrl);
            // 创建链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(10 * 1000);

            if (conn.getResponseCode() != 200) {
                new RuntimeException("连接失败/链接失效/图片不存在");
            }
            inStream = conn.getInputStream();
            int len = -1;
            while ((len = inStream.read(data)) != -1) {
                outPut.write(data, 0, len);
            }
            inStream.close();
        } catch (IOException e) {
            log.error("imageUrlToBase64Str Exception", e);
        } finally {
            try {
                if (inStream != null)
                    inStream.close();
            } catch (Exception e) {
            }
        }
        // 对字节数组Base64编码
        byte[] encode = Base64.getEncoder().encode(outPut.toByteArray());
        return new String(encode);
    }
}
